const config = require("../../config")
const moment = require("../../lib/moment-local")
require("../../lib/moment-duration-format")(moment)
const util = require("../../util")
const oss = require("../../oss/main")

let playingTimeInterval
let recordingTimeInterval
let selectIndex
let popupIndex

const app = getApp()

Page({
  data: {
    userInfo: null,
    list: [],
    recording: false,
    recordingTime: 0,
    recordingTimeHum: '00:00:00',
    playing: false,
    playingTime: 0,
    playingTimeHum: '00:00:00',
    selectItem: null,
    popupItem: null,
    showTitlePopup: false
  },
  onHide: function () {
    this.clearIng()
  },
  viewUserInfo: function () {
    this.setData({
      userInfo: app.globalData.userInfo
    })
    wx.setNavigationBarTitle({
      title: app.globalData.userInfo.nickName + '的录音机'
    })
  },
  onLoad: function () {
    app.userInfoReadyCallback = this.viewUserInfo
    if (app.globalData.userInfo) {
      this.viewUserInfo()
    }

    app.sessionReadyCallback = this.getRecordingList
    if (app.globalData.session3rd) {
      console.log('direct getRecordingList')
      this.getRecordingList();
    }
  },
  // 调用 getUserInfo 获取头像昵称，会弹框
  getUserInfo: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    this.viewUserInfo()
  },
  clearIng: function () {
    if (this.data.playing) {
      this.stopVoice()
    } else if (this.data.recording) {
      this.stopRecordUnexpectedly()
    }
  },
  getRecordingList: function () {
    wx.request({
      url: config.server + '/recording/list/' + app.globalData.session3rd,
      success: (result) => {
        if (result.statusCode != 200) {
          console.error("getRecordingList:" + result.data.message)
          return
        }
        this.renderList(result.data)
      },
      fail: console.error,
    })
  },
  renderList(data) {
    const list = data.map(item => {
      item.createTimeHum = moment(item.createTime).format('lll')
      item.recordTimeHum = moment.duration(item.recordTime, 'seconds').format("mm:ss", { trim: false })
      return item
    })
    this.setData({
      list: list
    })
  },
  setPlayingTime: function (playingTime) {
    this.setData({
      playingTime: playingTime,
      playingTimeHum: util.formatTime(playingTime)
    })
  },
  setRecordingTime: function (recordingTime) {
    this.setData({
      recordingTime: recordingTime,
      recordingTimeHum: util.formatTime(recordingTime)
    })
  },
  selectItem: function (index) {
    this.clearIng()
    this.data.list.forEach(function (item) {
      item.select = false
    })
    if (selectIndex === index) {
      this.renderList(this.data.list)
      this.setData({
        selectItem: null
      })
      selectIndex = null
      return
    }
    selectIndex = index
    let item = this.data.list[index]
    item.select = true
    this.renderList(this.data.list)
    this.setData({
      selectItem: item
    })
  },
  tapItem: function (e) {
    this.selectItem(e.currentTarget.dataset.index)
  },
  tapItemLong: function (e) {
    this.clearIng()
    popupIndex = e.currentTarget.dataset.index
    this.setData({
      popupItem: this.data.list[popupIndex],
      showTitlePopup: true
    })
  },
  keyTitle: function (e) {
    this.data.popupItem.title = e.detail.value
  },
  saveTitle: function () {
    this.updateRecording(this.data.popupItem, popupIndex)
    this.setData({
      showTitlePopup: false
    })
  },
  cancelTitle: function () {
    this.setData({
      showTitlePopup: false
    })
  },
  updateRecording: function (item, index) {
    Object.assign(item, { session3rd: app.globalData.session3rd})
    wx.request({
      method: "PUT",
      url: config.server + '/recording',
      data: item,
      success: (result) => {
        if (result.statusCode != 200) {
          console.error(result.data.message)
          return
        }
        this.data.list[index] = item
        this.renderList(this.data.list)
        this.setData({
          showTitlePopup: false
        })
      },
      fail: console.error
    })
  },
  startRecord: function () {
    this.setData({
      recording: true,
      selectItem: null,
    })
    this.setRecordingTime(0)
    recordingTimeInterval = setInterval(()=> {
      this.setRecordingTime(this.data.recordingTime + 1)
    }, 1000)
    wx.startRecord({
      success: (result) => {
        // https://goo.gl/PDMLb9 #5floor
        wx.saveFile({
          tempFilePath: result.tempFilePath,
          success: (result2) => {
            wx.request({
              method: "POST",
              url: config.server + '/recording',
              data: {
                session3rd: app.globalData.session3rd,
                title: "临时" + this.data.list.length,
                recordTime: this.data.recordingTime,
                tempFilePath: result2.savedFilePath,
                upload: false
              },
              success: (result3) => {
                if (result3.statusCode != 200) {
                  console.error(result3.data.message)
                  return
                }
                result3.data.select = true
                this.data.list.unshift(result3.data)
                this.renderList(this.data.list)
                this.selectItem(0)
              },
              fail: console.error,
            })
          }
        })
      },
      fail: console.error,
      complete: () => {
        clearInterval(recordingTimeInterval)
        this.setData({ recording: false })
      }
    })
  },
  stopRecord: function () {
    wx.stopRecord()
  },
  stopRecordUnexpectedly: function () {
    wx.stopRecord({
      success: ()=> {
        clearInterval(recordingTimeInterval)
        this.setData({ recording: false })
      }
    })
  },
  playVoice: function () {
    if (!this.data.selectItem) return
    wx.getSavedFileInfo({
      filePath: this.data.selectItem.tempFilePath,
      success: (res) => {
        this.playVoiceImpl(this.data.selectItem.tempFilePath)
      },
      fail: (res) => {
        oss.downloadFile(
          this.data.selectItem._id,
          (tempFilePath) => {
            this.playVoiceImpl(tempFilePath)
          },
          function (err) {
            console.error(err)
            wx.showToast({
              title: `${err.statusCode} ${err.errMsg}`,
              icon: 'success',
              duration: 1000
            })
          }
        )
      }
    })
  },
  playVoiceImpl: function (tempFilePath) {
    this.setPlayingTime(0)
    playingTimeInterval = setInterval(()=> {
      this.setPlayingTime(this.data.playingTime + 1)
    }, 1000)
    this.setData({ playing: true })

    wx.playVoice({
      filePath: tempFilePath,
      complete: ()=> {
        // clearInterval(playingTimeInterval)
        // this.setData({ playing: false })
      }
    })

    setTimeout(()=> {
      clearInterval(playingTimeInterval)
      this.setData({ playing: false })
    }, this.data.selectItem.recordTime*1000)
  },
  pauseVoice: function () {
    wx.pauseVoice()
    clearInterval(playingTimeInterval)
    this.setData({ playing: false })
  },
  stopVoice: function () {
    wx.stopVoice()
    clearInterval(playingTimeInterval)
    this.setData({ playing: false })
    this.setPlayingTime(0)
  },
  trashRecording: function () {
    if (!this.data.selectItem) return
    this.clearIng()

    wx.showModal({
      title: '删除',
      content: `确定删除 ${this.data.selectItem.title}?`,
      success: (res)=> {
        if (res.confirm) {
          wx.request({
            method: "DELETE",
            url: config.server + '/recording',
            data: {
              session3rd: app.globalData.session3rd,
              _id: this.data.selectItem._id
            },
            success: (result) => {
              wx.showToast({
                title: `${this.data.selectItem.title} 已删除`,
                icon: 'success',
                duration: 1000
              })
              this.getRecordingList()
              this.setData({ selectItem: null })
            },
            fail: console.error
          })
        } else if (res.cancel) {
          // 用户点击取消
        }
      }
    })
  },
  uploadVoice: function () {
    if (!this.data.selectItem) return
    oss.uploadFile(
      this.data.selectItem._id,
      this.data.selectItem.tempFilePath,
      () => {
        wx.showToast({
          title: '上传成功',
          icon: 'success',
          duration: 1000
        })
        this.data.selectItem.upload = true
        this.setData({
          selectItem: this.data.selectItem
        })
        this.updateRecording(this.data.selectItem, selectIndex)
      },
      function (err) { console.error(err) }
    )
  }
})
